<template>
  <div id="userManagePage">
    <!-- 搜索表单 -->
    <a-form layout="inline" :model="searchParams" @finish="doSearch">
      <a-form-item label="账号">
        <a-input v-model:value="searchParams.userAccount" placeholder="输入账号" />
      </a-form-item>
      <a-form-item label="用户名">
        <a-input v-model:value="searchParams.userName" placeholder="输入用户名" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit">搜索</a-button>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="showAddModal">新增用户</a-button>
      </a-form-item>
    </a-form>
    <a-divider />
    <!-- 表格 -->
    <a-table
      :columns="columns"
      :data-source="data"
      :pagination="pagination"
      @change="doTableChange"
    >
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.dataIndex === 'index'">
          {{ ((searchParams.pageNum ?? 1) - 1) * (searchParams.pageSize ?? 10) + index + 1 }}
        </template>
        <template v-else-if="column.dataIndex === 'userAvatar'">
          <a-image :src="record.userAvatar" :width="120" />
        </template>
        <template v-else-if="column.dataIndex === 'userRole'">
          <div v-if="record.userRole === 'admin'">
            <a-tag color="green">管理员</a-tag>
          </div>
          <div v-else>
            <a-tag color="blue">普通用户</a-tag>
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button type="primary" size="small" @click="showEditModal(record)">编辑</a-button>
            <a-button danger size="small" @click="doDelete(record.id)">删除</a-button>
          </a-space>
        </template>
      </template>
    </a-table>
  </div>

  <!-- 新增/编辑用户模态框 -->
  <a-modal
    v-model:open="modalVisible"
    :title="isEdit ? '编辑用户' : '新增用户'"
    @ok="handleModalOk"
    @cancel="handleModalCancel"
  >
    <a-form :model="modalForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
      <a-form-item label="用户名" :rules="[{ required: true, message: '请输入用户名' }]">
        <a-input v-model:value="modalForm.userName" placeholder="请输入用户名" />
      </a-form-item>
      <a-form-item label="账号" :rules="[{ required: true, message: '请输入账号' }]">
        <a-input
          v-model:value="modalForm.userAccount"
          placeholder="请输入账号"
          :disabled="isEdit"
        />
      </a-form-item>
      <a-form-item label="头像">
        <a-input v-model:value="modalForm.userAvatar" placeholder="请输入头像URL" />
      </a-form-item>
      <a-form-item label="简介">
        <a-textarea v-model:value="modalForm.userProfile" placeholder="请输入用户简介" :rows="3" />
      </a-form-item>
      <a-form-item label="用户角色">
        <a-select v-model:value="modalForm.userRole" placeholder="请选择用户角色">
          <a-select-option value="user">普通用户</a-select-option>
          <a-select-option value="admin">管理员</a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { addUser, deleteUser, listUserVoByPage, updateUser } from '@/api/userController.ts'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'

const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    width: 80,
  },
  {
    title: '账号',
    dataIndex: 'userAccount',
  },
  {
    title: '用户名',
    dataIndex: 'userName',
  },
  {
    title: '头像',
    dataIndex: 'userAvatar',
  },
  {
    title: '简介',
    dataIndex: 'userProfile',
  },
  {
    title: '用户角色',
    dataIndex: 'userRole',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '操作',
    key: 'action',
  },
]
// 数据
const data = ref<API.UserVO[]>([])
const total = ref(0)
// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.pageNum ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total: number) => `共 ${total} 条`,
    showQuickJumper: true,
    pageSizeOptions: ['10', '20', '50', '100'],
    showSizeChangerText: '条/页',
  }
})

// 表格变化处理
const doTableChange = (page: { current: number; pageSize: number }) => {
  searchParams.pageNum = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

// 搜索条件
const searchParams = reactive<API.UserQueryRequest>({
  pageNum: 1,
  pageSize: 10,
})

// 模态框相关状态
const modalVisible = ref(false)
const isEdit = ref(false)
const modalForm = reactive<API.UserAddRequest & { id?: number }>({
  userName: '',
  userAccount: '',
  userAvatar: '',
  userProfile: '',
  userRole: 'user',
})

// 获取数据
const fetchData = async () => {
  const res = await listUserVoByPage({
    ...searchParams,
  })
  if (res.data.data) {
    data.value = res.data.data.records ?? []
    total.value = res.data.data.totalRow ?? 0
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
}
// 获取数据
const doSearch = () => {
  // 重置页码
  searchParams.pageNum = 1
  fetchData()
}
// 删除数据
const doDelete = async (id: number) => {
  if (!id) {
    return
  }
  const res = await deleteUser({ id })
  if (res.data.code === 0) {
    message.success('删除成功')
    // 刷新数据
    fetchData()
  } else {
    message.error('删除失败')
  }
}

// 显示新增模态框
const showAddModal = () => {
  isEdit.value = false
  modalVisible.value = true
  // 重置表单
  Object.assign(modalForm, {
    userName: '',
    userAccount: '',
    userAvatar: '',
    userProfile: '',
    userRole: 'user',
  })
}

// 显示编辑模态框
const showEditModal = (record: API.UserVO) => {
  isEdit.value = true
  modalVisible.value = true
  // 填充表单数据
  Object.assign(modalForm, {
    id: record.id,
    userName: record.userName,
    userAccount: record.userAccount,
    userAvatar: record.userAvatar,
    userProfile: record.userProfile,
    userRole: record.userRole,
  })
}

// 模态框确认
const handleModalOk = async () => {
  try {
    if (isEdit.value) {
      // 编辑用户
      const res = await updateUser({
        id: modalForm.id,
        userName: modalForm.userName,
        userAvatar: modalForm.userAvatar,
        userProfile: modalForm.userProfile,
        userRole: modalForm.userRole,
      })
      if (res.data.code === 0) {
        message.success('编辑成功')
        modalVisible.value = false
        fetchData()
      } else {
        message.error('编辑失败，' + res.data.message)
      }
    } else {
      // 新增用户
      const res = await addUser({
        userName: modalForm.userName,
        userAccount: modalForm.userAccount,
        userAvatar: modalForm.userAvatar,
        userProfile: modalForm.userProfile,
        userRole: modalForm.userRole,
      })
      if (res.data.code === 0) {
        message.success('新增成功')
        modalVisible.value = false
        fetchData()
      } else {
        message.error('新增失败，' + res.data.message)
      }
    }
  } catch {
    message.error('操作失败')
  }
}

// 模态框取消
const handleModalCancel = () => {
  modalVisible.value = false
}

// 页面加载时请求一次
onMounted(() => {
  fetchData()
})
</script>

<style scoped></style>
